/**
 * 腾讯短信
 * Created by haoran.shu on 2018/7/31 15:31.
 */
const utils = require('./utils');
const crypto = require('crypto');
const qs = require('querystring');
const logger = require('log4js').getLogger('TLSSMS');
const r2 = require('r2');

const APPID = '1400108305';
const APPKEY = '5da43bc4e82c5ea699843a88fde9099c';
const SMSURL = 'https://yun.tim.qq.com/v5/tlssmssvr/sendsms';

/**
 * 发送验证码
 * @param tel  发送验证码的手机号
 * @param code 验证码
 */
module.exports = (tel, code) => {
  let unixTime = parseInt(Date.now() / 1000, 10);
  let random = utils.random(10);
  let sha256 = crypto.createHash('sha256');
  sha256.update(qs.stringify({
    appkey: APPKEY,
    random: random,
    time: unixTime,
    mobile: tel
  }));
  let sig = sha256.digest('hex');
  // 发送验证码短信
  r2.post(`${SMSURL}?sdkappid=${APPID}&random=${random}`, {json: {
      params: [code],
      sig: sig,
      tel: {
        "mobile": tel,
        "nationcode": "86"
      },
      time: unixTime,
      tpl_id: 165651
    }})
  .text.then(d => {
    logger.info(d);
  }).catch(e => {
    logger.error('tencent sms error!');
    logger.error(e);
  });
};
